package com.sky.controller.admin;


import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {

//      目标：获取文件上传到H:\heima中，并且使用UUID生成唯一文件名
//      1.生成唯一文件名
        String originalFilename = file.getOriginalFilename();
//      截取的拓展名.jpg
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
//      生成UUID加密
        String fileName = UUID.randomUUID() + extName;
//      2.保存到磁盘上
//      本地存储 file.transferTo(new File("H:\\heima\\img\\"+fileName));
        try {
//      上传到OSS
            String path = aliOssUtil.upload(file.getBytes(), fileName);
//      3.返回成功
            return Result.success(path);
        } catch (IOException e) {
            log.error("上传到OSS失败：{}", e.getMessage());
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }


    }

}
